/*
 * Copyright 2012 Marsrutai.lt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.fragment;

import lt.marsrutai.mobile.android.AppContext;
import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.bundle.ScopeDownloadBundleHolder;
import lt.marsrutai.mobile.android.cache.UpdateCacheRequest;
import lt.marsrutai.mobile.android.cache.UpdateCacheRequest.Section;
import lt.marsrutai.mobile.android.util.PreferenceUtils;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ProgressBar;

import com.actionbarsherlock.app.SherlockFragment;

public class ScopeDownloadFragment extends SherlockFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.scope_download_layout, null);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setupView();
    }

    private void setupView() {
        CheckBox downloadDataCheckbox = (CheckBox) getActivity().findViewById(R.id.download_data);
        if (null == downloadDataCheckbox) {
            return;
        }

        downloadDataCheckbox
                .setChecked(null != new ScopeDownloadBundleHolder(ScopeDownloadFragment.this.getArguments()).getStoredVersion());
        downloadDataCheckbox.setOnClickListener(new OnClickListener() {

            /**
             * Handle logic here instead of onCheckedChangeListener because when one fragment is swapped with the
             * another onResume is called on checkbox. This in itself checks its saved state and calls OnCheckedChanged
             * listener if there is any. So actions get repeaed after fragments onResume method is called.
             */
            @Override
            public void onClick(View v) {
                ScopeDownloadBundleHolder holder = new ScopeDownloadBundleHolder(ScopeDownloadFragment.this.getArguments());
                CheckBox checkbox = ((CheckBox) v);

                UpdateCacheRequest updateRequest = new UpdateCacheRequest(holder.getScopeFolder(), holder.getScopeName(), Section.SCHEDULES);

                if (checkbox.isChecked()) {
                    AppContext.getCacheUpdateManager().performUpdate(ScopeDownloadFragment.this.getActivity(), updateRequest);

                    // Do not show data download advice when entering schedules activity anymore.
                    PreferenceUtils.setBooleanPreferenceValue(ScopeDownloadFragment.this.getActivity(),
                            PreferenceUtils.SCHEDULE_ACTIVITY_OPENED, Boolean.TRUE);

                }
                else {
                    if (AppContext.getDataCacheUpdater().isScopeStored(holder.getScopeFolder())) {
                        AppContext.getCacheUpdateManager().showScopeDeleteConfirmationDialog(ScopeDownloadFragment.this.getActivity(),
                                holder.getScopeFolder(), checkbox);
                    }
                    else {
                        // Notify data download service that we do not want to download this scope anymore.
                        AppContext.getCacheUpdateManager().cancelUpdate(ScopeDownloadFragment.this.getActivity(), updateRequest);
                    }
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

        ScopeDownloadBundleHolder holder = new ScopeDownloadBundleHolder(ScopeDownloadFragment.this.getArguments());

        // Progress bar is still visible when download is finished while other activity is being active.
        // Hide progress bar whenever resuming this activity.
        ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.download_progress);
        if (null != progressBar) {
            progressBar.setVisibility(View.INVISIBLE);
        }

        CheckBox downloadDataCheckbox = (CheckBox) getActivity().findViewById(R.id.download_data);
        if (null != downloadDataCheckbox) {
            downloadDataCheckbox.setEnabled(true);
            downloadDataCheckbox.setChecked(AppContext.getDataCacheUpdater().isScopeStored(holder.getScopeFolder()));
        }
    }
}
